package com.bysc.joinservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.constant.RedisConstant;
import com.bysc.commonutils.utils.DateUtil;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.commonutils.vo.JoinForm;
import com.bysc.joinservice.entity.vo.JoinFormQueryVo;
import com.bysc.joinservice.service.JoinFormService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kkk
 * @since 2024-05-28
 */
@Api(tags = "社团报名功能管理")
@RestController
@RefreshScope   //支持Nacos的动态刷新功能
@RequestMapping("/joinservice/join-form")
public class JoinFormController {
    @Value("${join.searchtime}")
    private String time;
    @Autowired
    private JoinFormService joinFormService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "根据token新增报名（前台要传clubId）")
    @PostMapping("/addJoinFormByToken")
    public Results createJoinFormByToken(@RequestBody JoinForm joinForm, HttpServletRequest request) {
        try {
            if (!checkTime()) {// 已到查询时间禁止操作
                throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_TIME_FAIL);
            }
            String userId = JwtUtils.getMemberIdByJwtToken(request);
            joinForm.setUserId(userId);
            joinFormService.save(joinForm);
            return Results.ok().message(MessageConstant.ADD_JOINFORM_SUCCESS);
        } catch (BaiYunException e) {
            throw e;
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.ADD_JOINFORM_FAIL);
        }
    }


    /*
    * TODO 这里要改list查询多结果
    * */
    @ApiOperation(value = "根据token获取录取结果")
    @PostMapping("/getJoinFormStatusByToken")
    public Results getJoinFormStatusByToken(HttpServletRequest request) {
        if (checkTime()) {// 未到查询时间禁止查询
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_TIME_FAIL);
        }
        JoinForm joinForm = new JoinForm();
        try {
            String userId = JwtUtils.getMemberIdByJwtToken(request);
            String key = RedisConstant.JOIN_FORM + userId;
            if (redisTemplate.hasKey(key)) {
                joinForm = (JoinForm) redisTemplate.opsForValue().get(key);
            }
            if (joinForm == null || joinForm.getId() == null) {//缓存查不到
                joinForm = joinFormService.getOne(new QueryWrapper<JoinForm>().eq("user_id", userId));
                if (joinForm == null || joinForm.getId() == null) {//数据库查不到
                    throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_FORM_FAIL);
                }
                redisTemplate.opsForValue().set(key, joinForm, RedisConstant.KEY_TIMEOUT, TimeUnit.SECONDS);
            }
            return Results.ok().data("joinForm", joinForm).message(MessageConstant.QUERY_JOINFORM_SUCCESS);
        } catch (BaiYunException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_JOINFORM_FAIL);
        }
    }

    @ApiOperation(value = "根据token获取报名表信息（学生查询报名结果）")
    @PostMapping("/getJoinFormByToken")
    public Results getJoinFormByToken(HttpServletRequest request) {
        try {
            List<JoinForm> formList = null;
            String userId = JwtUtils.getMemberIdByJwtToken(request);
            if(!StringUtils.isEmpty(userId)){
                formList=joinFormService.list(new QueryWrapper<JoinForm>().eq("user_id", userId));
            }
            if(formList.size()<0){//数据库查不到
                throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_FORM_FAIL);
            }
            return Results.ok().data("joinForm", formList).message(MessageConstant.QUERY_JOINFORM_SUCCESS);
        } catch (BaiYunException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_JOINFORM_FAIL);
        }
    }

    @ApiOperation(value = "根据token修改报名表信息")
    @PutMapping("/updateJoinFormByToken")
    public Results updateJoinFormByToken(@RequestBody JoinForm joinForm, HttpServletRequest request) {
        try {
            if (!checkTime()) {// 已到查询时间禁止操作
                throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_TIME_FAIL);
            }
            String userId = JwtUtils.getMemberIdByJwtToken(request);
            joinFormService.update(joinForm, new QueryWrapper<JoinForm>().eq("user_id", userId));
            return Results.ok().message(MessageConstant.EDIT_JOINFORM_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_JOINFORM_FAIL);
        }
    }

    @ApiOperation(value = "根据报名表id修改报名表信息")
    @PutMapping("/updateJoinFormById")
    public Results updateJoinFormById(@RequestBody JoinForm joinForm) {
        try {
            joinFormService.updateById(joinForm);
            return Results.ok().message(MessageConstant.EDIT_JOINFORM_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_JOINFORM_FAIL);
        }
    }


    @ApiOperation(value = "根据token删除报名表")
    @DeleteMapping("/daleteFormByToken")
    public Results daleteFormByToken(HttpServletRequest request) {
        try {
            if (!checkTime()) {// 已到查询时间禁止操作
                throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_TIME_FAIL);
            }
            String userId = JwtUtils.getMemberIdByJwtToken(request);
            joinFormService.remove(new QueryWrapper<JoinForm>().eq("user_id", userId));
            return Results.ok().message(MessageConstant.DELETE_JOINFORM_SUCCESS);
        } catch (BaiYunException e) {
            throw e;
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_JOINFORM_FAIL);
        }
    }

    @ApiOperation(value = "根据报名表id删除报名表")
    @DeleteMapping("/daleteFormById/{id}")
    public Results daleteFormById(@PathVariable String id) {
        try {
            joinFormService.removeById(id);
            return Results.ok().message(MessageConstant.DELETE_JOINFORM_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_JOINFORM_FAIL);
        }
    }

//    @ApiOperation(value = "查找所有报名表")
//    @GetMapping("/getAllJoinForm")
//    public Results getAllJoinForm() {
//        try {
//            List<JoinForm> list = joinFormService.list(null);
//            return Results.ok().data("list", list).message(MessageConstant.QUERY_JOINFORM_SUCCESS);
//        } catch (Exception e) {
//            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_JOINFORM_FAIL);
//        }
//    }

    @ApiOperation(value = "带条件分页查找报名表（后台管理员查询）")
    @PostMapping("/getJoinFormByPage/{page}/{limit}")
    public Results getJoinFormByPage(@ApiParam(name = "page", value = "查询页数", required = true)
                                     @PathVariable Integer page, @ApiParam(name = "limit", value = "查询数量", required = true)
                                     @PathVariable Integer limit, @ApiParam(name = "queryVo", value = "查询条件", required = false) JoinFormQueryVo queryVo,HttpServletRequest request) {
        try {
            String TOKEN_clubId= JwtUtils.getClubIdByJwtToken(request);
            Page<JoinForm> page1 = new Page<>(page, limit);
            LambdaQueryWrapper<JoinForm> wrapper = new LambdaQueryWrapper<>();
            if(!StringUtils.isEmpty(TOKEN_clubId)){
                wrapper.eq(JoinForm::getClubId, TOKEN_clubId);
            }
            IPage<JoinForm> page2 = joinFormService.page(page1, wrapper);
            return Results.ok().data("page", page2).message(MessageConstant.QUERY_JOINFORM_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_JOINFORM_FAIL);
        }
    }

    /**
     * 判断当前时间与查询时间，true为未到时间，false为已到时间
     *
     * @return
     */
    private boolean checkTime() {
        Date date = DateUtil.formatD(time);
        return date.compareTo(new Date()) > 0;
    }



}

